/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package rs_GUI;


import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
//import javax.swing.DefaultListCellRenderer;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import pojos.Playlist;
import pojos.Song;

/**
 *
 * @author Mastroperrou
 */


public class PlayLists_MainPanel extends javax.swing.JPanel {
    //Πεδία
    RadioStationParentFrame frame;
    EntityManager em;
    private int row;
    private boolean cancelSave= false;//Το θέτουμε true όταν πατάμε το κουμπί ενημέρωση, ενω
                                        //το θέτουμε false όταν πατάμε το κουμπί εισαγωγή
    private Date neaDate = new Date();
    private String fname;
    
    JMenuBar menu = new JMenuBar();
    JMenu  jMenu1 = new JMenu("Μενού");  
    
    /**
     * Creates new form WelcomeJPanel
     */
    public PlayLists_MainPanel(RadioStationParentFrame frame, EntityManager em) {
        this.frame = frame;
        this.em = em;
        initComponents();
       
        JMenuItem newPlaylistItem = new JMenuItem("Δημιουργία");
        newPlaylistItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newPlaylistItemActionPerformed(evt);
            }
        });
        jMenu1.add(newPlaylistItem);
        
        JMenuItem exportXMLItem = new JMenuItem("Εξαγωγή Λίστας σε XML");
        exportXMLItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportXMLItemActionPerformed(evt);
            }
        });
        jMenu1.add(exportXMLItem);
        
        JMenuItem importXMLItem = new JMenuItem("Εισαγωγή Λίστας από XML");
        importXMLItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importXMLItemActionPerformed(evt);
            }
        });
        jMenu1.add(importXMLItem);
              
        JMenuItem exitItem = new JMenuItem("Έξοδος");
        exitItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitItemActionPerformed(evt);
            }
        });
        jMenu1.add(exitItem);
               
        menu.add(jMenu1);
        frame.setJMenuBar(menu);
    }
    
    private void newPlaylistItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.jCreatePlayListActionPerformed(evt);
    }      
     
    private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.exitButtonActionPerformed(evt);
    } 
    
    private void exportXMLItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.exportXMLActionPerformed(evt);
    } 
    
    private void importXMLItemActionPerformed(java.awt.event.ActionEvent evt) {                                           
        this.importXMLActionPerformed(evt);
    } 

    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        dateChooserPanel1 = new com.toedter.calendar.demo.DateChooserPanel();
        playlistQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT p FROM Playlist p");
        playlistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(playlistQuery.getResultList());
        playlist1 = new pojos.Playlist();
        jCreatePlayList = new javax.swing.JButton();
        jModifyPlayList = new javax.swing.JButton();
        jDeletePlayList = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPlayListTable = new javax.swing.JTable();
        mainLabel = new javax.swing.JLabel();
        importXML = new javax.swing.JButton();
        exportXML = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setPreferredSize(new java.awt.Dimension(610, 445));

        jCreatePlayList.setText("ΔΗΜΙΟΥΡΓΙΑ");
        jCreatePlayList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCreatePlayListActionPerformed(evt);
            }
        });

        jModifyPlayList.setText("ΕΝΗΜΕΡΩΣΗ");
        jModifyPlayList.setMaximumSize(new java.awt.Dimension(113, 23));
        jModifyPlayList.setMinimumSize(new java.awt.Dimension(113, 23));
        jModifyPlayList.setPreferredSize(new java.awt.Dimension(113, 23));
        jModifyPlayList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jModifyPlayListActionPerformed(evt);
            }
        });

        jDeletePlayList.setText("ΔΙΑΓΡΑΦΗ");
        jDeletePlayList.setMaximumSize(new java.awt.Dimension(113, 23));
        jDeletePlayList.setMinimumSize(new java.awt.Dimension(113, 23));
        jDeletePlayList.setPreferredSize(new java.awt.Dimension(113, 23));
        jDeletePlayList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jDeletePlayListActionPerformed(evt);
            }
        });

        exitButton.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        exitButton.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        exitButton.setLabel("ΕΞΟΔΟΣ");
        exitButton.setMaximumSize(new java.awt.Dimension(113, 23));
        exitButton.setMinimumSize(new java.awt.Dimension(113, 23));
        exitButton.setPreferredSize(new java.awt.Dimension(113, 23));
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        jPlayListTable.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
        jPlayListTable.setForeground(new java.awt.Color(51, 51, 51));
        jPlayListTable.setName(""); // NOI18N
        jPlayListTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playlistList, jPlayListTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${creation}"));
        columnBinding.setColumnName("Ημ. Δημιουργίας");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jPlayListTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPlayListTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jPlayListTable);
        if (jPlayListTable.getColumnModel().getColumnCount() > 0) {
            jPlayListTable.getColumnModel().getColumn(1).setPreferredWidth(0);
        }

        mainLabel.setText("PLAYLIST");

        importXML.setText("ΕΙΣΑΓΩΓΗ ΛΙΣΤΑΣ ΑΠΟ ΑΡΧΕΙΟ XML");
        importXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importXMLActionPerformed(evt);
            }
        });

        exportXML.setText("ΕΞΑΓΩΓΗ ΛΙΣΤΑΣ ΣΕ XML");
        exportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportXMLActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(251, 251, 251)
                .addComponent(mainLabel)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(exportXML, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(importXML)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                        .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jCreatePlayList, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jDeletePlayList, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(113, 113, 113)
                        .addComponent(jModifyPlayList, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1)
                    .addComponent(jSeparator1))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jCreatePlayList, jDeletePlayList, jModifyPlayList});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addComponent(mainLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jModifyPlayList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jDeletePlayList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCreatePlayList))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(exportXML, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(importXML, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {exitButton, exportXML, importXML});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jCreatePlayList, jDeletePlayList, jModifyPlayList});

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        frame.addPanelInMain(new EmptyMainPanel(frame));
        frame.addPanelInSide(new MainMenuSidePanel(frame, em));
    }//GEN-LAST:event_exitButtonActionPerformed

    private void jCreatePlayListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCreatePlayListActionPerformed
        //Δημιουργούμε μία νέα playlist
        playlist1 = new Playlist (null);
        playlist1.setCreation(neaDate);
        playlist1.setName("");
        
        try {
            //Νέα δοσοληψία
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            //Κάνε persist το playlist1 στη ΒΔ   
            em.persist(playlist1);
            //Ρίχτο στη ΒΔ
            em.flush();
            
            }
        }catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Σφάλμα βάσης...");
        }
        cancelSave = false;
        
        //Καλώ τη φόρμα PlayListManagement
        frame.addPanelInMain(new PlayListManagement(frame, em, playlist1, cancelSave));
        
    }//GEN-LAST:event_jCreatePlayListActionPerformed

    private void jModifyPlayListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jModifyPlayListActionPerformed
        // Βάζουμε στη μεταβλητή row τη γραμμή που επιλέξαμε
        row = jPlayListTable.getSelectedRow();
        
        // Αν δεν έχουμε επιλλέξει κάτι τότε βγάλε μήνυμα λάθους
        if (jPlayListTable.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "Επιλέξτε μία λίστα.", 
                                           "ERROR",
                                           JOptionPane.WARNING_MESSAGE);
        }
        else {
            cancelSave = true;
            //Βάλε στο album1 το επιλεγμένο άλμπουμ.
            playlist1 = playlistList.get(row);
            //Κάνε τον persist στη ΒΔ
            em.persist(playlist1);
            
            //Καλώ τη φόρμα PlayListManagement
            frame.addPanelInMain(new PlayListManagement(frame, em, playlist1, cancelSave));
        }
    }//GEN-LAST:event_jModifyPlayListActionPerformed

    private void jDeletePlayListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jDeletePlayListActionPerformed
        // Βάζουμε στη μεταβλητή row τη γραμμή που επιλέξαμε
        row = jPlayListTable.getSelectedRow();
        
        // Αν δεν έχουμε επιλλέξει κάτι τότε βγάλε μήνυμα λάθους
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "Επιλέξτε μία λίστα.", 
                                           "ERROR",
                                           JOptionPane.WARNING_MESSAGE);
        }
         else {
            // Μήνυμα επιβεβαίωσης της διαγραφής
            Object[] options = {"Ναι","Όχι"};
            Integer choice = JOptionPane.showOptionDialog(this,
            "Διαγραφή επιλεγμένης λίστας;",
            "Επιβεβαίωση διαγραφής",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);
            
            if (choice == JOptionPane.YES_OPTION){
                jDeletePlayList.setEnabled(false);
                //Βάλε στο album1 το άλμπουμ
                playlist1 = playlistList.get(row);
                
                try {
                    //Νέα δοσοληψία
                    if (!em.getTransaction().isActive()) {
                        em.getTransaction().begin();
                    }
                    
                    //Αφαιρούμε το album από τη βάση
                    em.remove(playlist1);
                    //Διαγράφουμε το album από τη λίστα με τους καλλιτέχνες
                    //που υπάρχει στον κώδικα της φόρμας
                    playlistList.remove(playlist1);
                           
                    //Τερματισμός δοσοληψίας
                    em.getTransaction().commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                        JOptionPane.showMessageDialog(null, "Σφάλμα βάσης...");
                    }
                
                for(Song s : playlist1.getSongList()){
                    s.getPlaylistList().remove(playlist1);
                }   
                jDeletePlayList.setEnabled(true); 
            }
        }
        
    }//GEN-LAST:event_jDeletePlayListActionPerformed

    private void jPlayListTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPlayListTableMouseClicked
        if(evt.getClickCount()==2){
            ActionEvent e = null;
           jModifyPlayListActionPerformed(e);
        }
    }//GEN-LAST:event_jPlayListTableMouseClicked

    private void exportXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportXMLActionPerformed
        // Βάζουμε στη μεταβλητή row τη γραμμή που επιλέξαμε
        row = jPlayListTable.getSelectedRow();
        
        // Αν δεν έχουμε επιλλέξει κάτι τότε βγάλε μήνυμα λάθους
        if (jPlayListTable.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "Επιλέξτε μία λίστα.", 
                                           "ERROR",
                                           JOptionPane.WARNING_MESSAGE);
        }
        else {
            String xmlName = null;
            boolean count=false;
            File f;
            
            //Ζητείται από το χρήστη να δώσει όνομα στο αρχείο xml
            do{
                //Έλεγχος για το άν το όνομα του αρχείου περιέχει απαγορευμένους χαρακτήρες
                if(count){
                JOptionPane.showMessageDialog(this, "Ένα όνομα αρχείου δεν πρέπει"+
                                                    "\nνα περιέχει κάποιον από τους παρακάτω"+
                                                    "\nχαρακτήρες:\n"+
                                                    "/, \\, :, *, ?, \", <, >, |"+
                                                    "\nή να είναι κενό.", 
                                           "ERROR",
                                           JOptionPane.WARNING_MESSAGE);
                }xmlName = JOptionPane.showInputDialog(this, "Δώστε όνομα στο νέο αρχείο.");
                //Έλεγχος αν ο χρήστης πατήσει το cancel ή κλέισει το JOptionPane
                if(xmlName == null){
                    return;
                }
                count=true;
            }while(xmlName.contains("/")||xmlName.contains("\\")
                ||xmlName.contains(":")||xmlName.contains("*")
                ||xmlName.contains("?")||xmlName.contains("\"")
                ||xmlName.contains("<")||xmlName.contains(">")
                ||xmlName.contains("|")||xmlName.equals(""));
                
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new java.io.File("."));
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            // disable the "All files" option.
            chooser.setAcceptAllFileFilterUsed(false);
            
            //Κλήση της wach που απενεργοποιεί την εισαγωγή directory
            //χειροκίνητα από το χρήστη
            Wach.watch(chooser);

            int returnVal = chooser.showDialog(frame, "Σώσε το Εδώ");

            if(returnVal == JFileChooser.APPROVE_OPTION) {
                f = chooser.getSelectedFile();

                String xmlPath = f.getAbsolutePath();
                System.out.println("\nYou chose this name: " +
                    xmlName);
                System.out.println("\nYou chose to save this file: " +
                    f.getAbsolutePath());
                //Βάλε στο playlist1 την επιλεγμένη λίστα.
                playlist1 = playlistList.get(row);

                //Κάλεσε τη μέθοδο createXml που βρίσκεται στην κλάση XmlManagement
                XmlManagement xmlM = new XmlManagement(em);
                xmlM.createXml(playlist1, fname, xmlPath, xmlName);
            }
        }
    }//GEN-LAST:event_exportXMLActionPerformed

    private void importXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importXMLActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "xml files (*.xml)", "xml");
        chooser.setFileFilter(filter);
        chooser.setCurrentDirectory(new java.io.File("."));
        
        //Κλήση της wach που απενεργοποιεί την εισαγωγή directory 
        //χειροκίνητα από το χρήστη
        Wach.watch(chooser);
        int returnVal = chooser.showOpenDialog(frame);
       
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            File f = chooser.getSelectedFile();
            String xmlName = f.getName();
            String directory = f.getAbsolutePath();
            System.out.println("\nYou chose to open this file: " +
                directory);
            XmlManagement xmlM = new XmlManagement(em);
            Playlist rvalue = xmlM.readXml(f, xmlName);
            if(rvalue!=null){
                playlistList.add(rvalue);
            }
                
        }        
    }//GEN-LAST:event_importXMLActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.demo.DateChooserPanel dateChooserPanel1;
    private javax.swing.JButton exitButton;
    private javax.swing.JButton exportXML;
    private javax.swing.JButton importXML;
    private javax.swing.JButton jCreatePlayList;
    private javax.swing.JButton jDeletePlayList;
    private javax.swing.JButton jModifyPlayList;
    private javax.swing.JTable jPlayListTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel mainLabel;
    private pojos.Playlist playlist1;
    private java.util.List<pojos.Playlist> playlistList;
    private javax.persistence.Query playlistQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}